﻿using System;
using System.Collections.Generic;
using System.Text;
using DialectSoftware.Networking;
using System.Net;

//monetate
namespace WebFabricator.org.Management
{
    public delegate void ProbeCallBack(HELOResult result);

    public class SLSMPClient
    {
        public const int PORT = 1300;

        //public const int PORT = 1900;
        //public const string IP = "239.255.1.2";

        BroadcastClient _client;
        // _client = new BroadcastClient();
        //_client.Send(PORT, request.ToByteArray(), 50000);
        //_client.ErrorHandler += new BroadcastClient.BroadcastClientErrorHandler(ErrorHandler);

        //MulticastClient _client;


        public SLSMPClient()
        {
            _client = new BroadcastClient();
            _client.Receive += new AsyncNetworkCallBack(Receive);
            _client.ErrorHandler += new AsyncNetworkErrorCallBack(ErrorHandler);

            //_client = new MulticastClient();
            //_client.Receive += new AsyncNetworkCallBack(Receive);
            //_client.ErrorHandler += new MulticastClient.MulticastClientErrorHandler(ErrorHandler);
        }

        public void ProbeBegin(int timeOut=30000)
        {
            SLSMPRequest request = new SLSMPRequest(SLSMP.HELO,String.Empty);
            _client.Send(PORT, request.ToByteArray(), timeOut);
            //_client.Send(IPAddress.Parse(IP), PORT, request.ToByteArray(), 50000);
        }

        public event ProbeCallBack ProbeEnd;

        private void ErrorHandler(AsyncNetworkAdapter adapter, Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.Message);
        }

        private void Receive(AsyncNetworkAdapter adapter)
        {
            try
            {
                IEnumerable<SLSMPResponse> responses = SLSMPResponse.Parse(adapter);
                responses.ForEach(response =>
                {
                    switch (response.RequestMethod)
                    {
                        case SLSMP.HELO:
                            if (ProbeEnd != null)
                            {
                                HELOResult result = HELOResult.Parse(response.Data);
                                ProbeEnd.Invoke(result);
                            }
                            break;
                        default:
                            throw new NotImplementedException(response.RequestMethod.ToString());
                    }
                });
            }
            catch
            {

            }
            finally
            {
                
            }
        }   
       
    }
}
